package com.huluobo.lc.kotlinim1812a.contract.chat

import com.huluobo.lc.kotlinim1812a.adapter.EMCallbackAdapter
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import org.jetbrains.anko.doAsync

/**
 * @author Lc
 * @description:
 * @date :2021/6/29 10:19
 */
class ChatPresenter(val view: ChatContract.View) : ChatContract.Presenter {
    companion object {
        const val PAGE_SIZE = 10
    }

    val messages = mutableListOf<EMMessage>()
    override fun sendMessage(contact: String, message: String) {
        //创建一条消息
        val emMessage = EMMessage.createTxtSendMessage(message, contact)
        emMessage.setMessageStatusCallback(object : EMCallbackAdapter() {
            override fun onSuccess() {
                runOnUIThread { view.onSendMessageSuccess() }
            }

            override fun onError(code: Int, error: String?) {
                runOnUIThread { view.onSendMessageFailed() }
            }
        })
        messages.add(emMessage)
        view.onStartSendMessage()
        EMClient.getInstance().chatManager().sendMessage(emMessage)
    }

    override fun addMessage(username: String, messages: MutableList<EMMessage>?) {
        //加入当前的消息列表
        messages?.let { this.messages.addAll(it) }
        //更新消息为已读消息
        //获取跟当前联系的会话,然后标记会话里所有的消息状态为已读
        val conversation = EMClient.getInstance().chatManager().getConversation(username)
        conversation.markAllMessagesAsRead()

    }

    override fun loadMessage(username: String) {
        doAsync {
            val conversation = EMClient.getInstance().chatManager().getConversation(username)
            conversation.markAllMessagesAsRead()
            messages.addAll(conversation.allMessages)
            runOnUIThread { view.onMessageLoaded() }
        }
    }

    override fun loadMoreMessage(username: String) {
        doAsync {
            val conversation = EMClient.getInstance().chatManager().getConversation(username)
            val startMsgId = messages[0].msgId
            val loadMoreFromDB = conversation.loadMoreMsgFromDB(startMsgId, PAGE_SIZE)
            messages.addAll(0, loadMoreFromDB)
            runOnUIThread { view.onMoreMessageLoaded(loadMoreFromDB.size) }
        }
    }
}